package com.useeinfo.oa.open.admin;

import com.alibaba.fastjson.JSONObject;
import com.useeinfo.framework.sugar.data.QueryParam;
import com.useeinfo.framework.sugar.data.SelectVO;
import com.useeinfo.framework.sugar.tools.Configuration;
import com.useeinfo.framework.sugar.tools.StringConverters;
import com.useeinfo.oa.common.utils.ResultUtil.ResultDto;
import com.useeinfo.oa.common.utils.ResultUtil.ResultUtil;
import com.useeinfo.oa.modules.base.biz.ApplicationModuleBiz;
import com.useeinfo.oa.modules.base.biz.EnterpriseBiz;
import com.useeinfo.oa.modules.base.entity.ApplicationModule;
import com.useeinfo.oa.modules.base.entity.Enterprise;
import com.useeinfo.oa.modules.maintaining.entity.FacilityMaintain;
import com.useeinfo.oa.modules.security.biz.SystemUserBiz;
import com.useeinfo.oa.modules.security.entity.SystemUser;
import com.useeinfo.oa.modules.security.util.SessionKeyUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * @program: YiYouFuPlatform
 * @author: Taogq
 * @createDate: 2018-12-04
 * @createTime: 16:27:09
 * admin企业管理后台接口
 */
@Controller
@RequestMapping("/web/admin/enterprise")
public class EnterpriseAdminManageAction {
    static Logger logger = LoggerFactory.getLogger(EnterpriseAdminManageAction.class);

    @Autowired
    private EnterpriseBiz enterpriseBiz;
    @Autowired
    private ApplicationModuleBiz applicationModuleBiz;
    @Autowired
    private SystemUserBiz systemUserBiz;

    /**
     * list页面跳转
     *
     * @return
     */
    @RequestMapping("/list")
    public ModelAndView list() {

        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("pages/admin/enterprise/list");

        return modelAndView;
    }

    /**
     * 数据查询接口
     *
     * @param pageNowParam
     * @param pageSizeParam
     * @param enterpriseName
     * @param code
     * @return
     */
    @RequestMapping("/listJson")
    @ResponseBody
    public JSONObject listJson(@RequestParam(value = "pageNo", required = false) String pageNowParam,
                               @RequestParam(value = "pageSize", required = false) String pageSizeParam,
                               String enterpriseName, String code) {
        QueryParam queryParam = new QueryParam(pageNowParam, pageSizeParam);
        if (!StringConverters.null2String(enterpriseName).equals("")) {
            queryParam.getSqlMap().put("enterpriseName", enterpriseName);
        }
        if (!StringConverters.null2String(code).equals("")) {
            queryParam.getSqlMap().put("code", code);
        }
        SystemUser systemUser = systemUserBiz.getLoginUser();
        if (null != systemUser) {
            queryParam.getSqlMap().put("systemUserId", systemUser.getId().toString());
        }
        return enterpriseBiz.findJSONList(queryParam);
    }



    /**
     * 企业管理者详情
     *
     * @param id
     * @return
     */
    @RequestMapping("/sysUserDetailPage")
    public ModelAndView sysUserDetailPage(String id){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("enterpriseId",id);
        modelAndView.setViewName("pages/admin/enterprise/detail");
        return modelAndView;
    }

    @RequestMapping("/detailInfo")
    @ResponseBody
    public JSONObject detailInfo(String enterpriseId) {
        QueryParam queryParam = new QueryParam(-1,-1);
        queryParam.getSqlMap().put("enterpriseIds",enterpriseId);
        queryParam.getSqlMap().put("operationRole","enterprise");
        return systemUserBiz.findJQJSONList(queryParam);
    }

    /**
     * 删除用户
     */
    @RequestMapping("/deleteUser")
    @ResponseBody
    public ResultDto deleteUser(String id
    ) {
        try{
            SystemUser systemUser=systemUserBiz.findModel(StringConverters.null2Long(id));
            systemUserBiz.deleteLogic(systemUser);
        }catch (Exception e){
            return  ResultUtil.error("删除失败");
        }
        return ResultUtil.success();
    }


    /**
     * 编辑页面跳转
     *
     * @param id
     * @return
     */
    @RequestMapping("/editPage")
    public ModelAndView editPage(String id) {

        ModelAndView modelAndView = new ModelAndView();
        Enterprise enterprise = enterpriseBiz.findModel(StringConverters.null2Long(id));
        modelAndView.addObject("enterprise", enterprise);
        List<ApplicationModule> applicationModuleList = applicationModuleBiz.findList();
        modelAndView.addObject("applicationModuleList", applicationModuleList);
        modelAndView.setViewName("pages/admin/enterprise/edit");
        return modelAndView;
    }

    /**
     * 编辑页面跳转--编辑子企业
     *
     * @param id
     * @return
     */
    @RequestMapping("/editChildPage")
    public ModelAndView editChildPage(String id) {

        ModelAndView modelAndView = new ModelAndView();
        Enterprise enterprise = enterpriseBiz.findModel(StringConverters.null2Long(id));
        modelAndView.addObject("enterprise", enterprise);
        modelAndView.setViewName("pages/admin/enterprise/childEdit");
        return modelAndView;
    }

    /**
     * 编辑子企业————获取企业信息
     *
     * @param id
     * @return
     */
    @RequestMapping("/getEnterpriseMsg")
    @ResponseBody
    public ResultDto getEnterpriseMsg(String id) {

        return enterpriseBiz.getEnterpriseMsg(id);

        //Enterprise enterprise = enterpriseBiz.findModel(StringConverters.null2Long(id));

        // return ResultUtil.success();
    }


    /**
     * 数据保存接口
     *
     * @param enterprise
     * @return
     */
    @RequestMapping("/addOrUpdate")
    @ResponseBody
    public ResultDto addOrUpdate(Enterprise enterprise, String applicationIds, String parentId) {
        try {
            return enterpriseBiz.addOrUpdate(enterprise, applicationIds, parentId);
        } catch (Exception e) {
            logger.info(e.getMessage());
            return ResultUtil.error();
        }
    }


    /**
     * 获取企业-选择框
     */
    @RequestMapping("/getEnterpriseListMagic")
    @ResponseBody
    public List<SelectVO> getEnterpriseListMagic(@RequestParam(value = "q", required = false) String q,
                                                 @RequestParam(value = "id", required = false) String id) {
        List<SelectVO> selectVOS = new ArrayList<>();
        Enterprise enterprise = enterpriseBiz.findModel(StringConverters.ToLong(id));
        if (enterprise != null) {
            selectVOS.add(new SelectVO(enterprise.getEnterpriseName(), enterprise.getId() + ""));
        }
        QueryParam queryParam = new QueryParam(1, 20);
        queryParam.getSqlMap().put("magicLike", q);
        queryParam.getSqlMap().put("magicId", id);
        queryParam.getSqlMap().put("notFirstId", Configuration.getConfigurationByName("superEnterpriseId"));
        List<Enterprise> enterprises = enterpriseBiz.findList(queryParam);
        enterprises.forEach(enterprise1 -> selectVOS.add(new SelectVO(enterprise1.getEnterpriseName(), enterprise1.getId() + "")));
        return selectVOS;
    }

    /**
     * 获取企业-选择框
     */
    @RequestMapping("/getManyEnterpriseListMagic")
    @ResponseBody
    public List<SelectVO> getManyEnterpriseListMagic(@RequestParam(value = "q", required = false) String q,HttpServletRequest request,
                                                 @RequestParam(value = "id", required = false) String id) {
        List<SelectVO> selectVOS = new ArrayList<>();
        Enterprise enterprise = enterpriseBiz.findModel(StringConverters.ToLong(id));
        if (enterprise != null) {
            selectVOS.add(new SelectVO(enterprise.getEnterpriseName(), enterprise.getId() + ""));
        }
        SystemUser systemUser=SessionKeyUtils.getSessionUser(request);

        QueryParam queryParam = new QueryParam(1, 20);
        queryParam.getSqlMap().put("magicLike", q);
        queryParam.getSqlMap().put("magicId", id);
//        queryParam.getSqlMap().put("systemUserId", systemUser.getId()+"");
//        queryParam.getSqlMap().put("notFirstId", Configuration.getConfigurationByName("superEnterpriseId"));
        List<Enterprise> enterprises = enterpriseBiz.findList(queryParam);
        enterprises.forEach(enterprise1 -> selectVOS.add(new SelectVO(enterprise1.getEnterpriseName(), enterprise1.getId() + "")));
        return selectVOS;
    }


    /**
     * 获取企业-选择框
     */
    @RequestMapping("/getEnterpriseListMagicChangeUser")
    @ResponseBody
    public List<SelectVO> getEnterpriseListMagicChangeUser(HttpServletRequest request) {
        List<SelectVO> selectVOS = new ArrayList<>();
        SystemUser user = SessionKeyUtils.getSessionUser(request);
        if (user == null) {
            return selectVOS;
        }
        Set<Enterprise> enterpriseSet = user.getEnterpriseSet();
        enterpriseSet.forEach(enterprise1 -> selectVOS.add(new SelectVO(enterprise1.getEnterpriseName(), enterprise1.getId() + "")));
        return selectVOS;
    }

    /**
     * 编辑页面跳转--编辑子企业editChild.jsp
     *
     * @param id
     * @return
     */
    @RequestMapping("/addChildPage")
    public ModelAndView addChildPage(String id, String parentId) {

        ModelAndView modelAndView = new ModelAndView();
        Enterprise enterprise = enterpriseBiz.findModel(StringConverters.null2Long(id));
        modelAndView.addObject("enterprise", enterprise);
        modelAndView.addObject("parentId", parentId);
        List<ApplicationModule> applicationModuleList = applicationModuleBiz.findList();
        modelAndView.addObject("applicationModuleList", applicationModuleList);
        modelAndView.setViewName("pages/admin/enterprise/editChild");
        return modelAndView;
    }

    /**
     * 编辑页面跳转--编辑子企业editChild.jsp
     *
     * @param
     * @return
     */
    @RequestMapping("/saveChildPage")
    @ResponseBody
    public ResultDto saveChildPage(Enterprise enterprise, String parentId) {
        try {
            return enterpriseBiz.addOrUpdate(enterprise, parentId);
        } catch (Exception e) {
            logger.info(e.getMessage());
            return ResultUtil.error();
        }
    }

    /**
     * 获取所有企业数据
     */
    @RequestMapping("/getEnterpriseTree")
    @ResponseBody
    public ResultDto getEnterpriseTree(@RequestParam(value = "sysCode", required = false) String sysCode) {
        return enterpriseBiz.getEnterpriseTree(sysCode);
    }


    /**
     * 企业管理者
     *
     * @param id
     * @return
     */
    @RequestMapping("/editSysUserPage")
    public ModelAndView editSysUserPage(String id) {

        ModelAndView modelAndView = new ModelAndView();
        Enterprise enterprise = enterpriseBiz.findModel(StringConverters.null2Long(id));
        modelAndView.addObject("enterprise", enterprise);
        modelAndView.setViewName("pages/admin/enterprise/editSysUser");
        return modelAndView;
    }




    /**
     * @param
     * @return
     */
    @RequestMapping("/saveEnterpriseSysUser")
    @ResponseBody
    public ResultDto saveEnterpriseSysUser(String enterpriseId, SystemUser systemUser) {
        try {
            return enterpriseBiz.addSysUserEnterprise(enterpriseId, systemUser);
        } catch (Exception e) {
            logger.info(e.getMessage());
            return ResultUtil.error();
        }
    }

    /**
     * @param
     * @return
     */
    @RequestMapping("/changeEnterprise")
    public ModelAndView changeEnterprise(HttpServletRequest request) {
        ModelAndView modelAndView = new ModelAndView();
        SystemUser systemUser = SessionKeyUtils.getSessionUser(request);
        if (systemUser == null) {
            modelAndView.setViewName("redirect:/security/loginout.action");
            return modelAndView;
        }
        modelAndView.setViewName("pages/admin/enterprise/changeEnterprise");
        return modelAndView;
    }

    /**
     * 切换企业
     */
    @RequestMapping("/toChangeEnterprise")
    @ResponseBody
    public ResultDto toChangeEnterprise(@RequestParam(value = "enterprise[]", required = false) List<String> enterprises,
                                        HttpServletRequest request) {
        if (CollectionUtils.isEmpty(enterprises)) {
            return ResultUtil.error("企业不存在！");
        }
        Enterprise enterprise = enterpriseBiz.findModel(StringConverters.ToLong(enterprises.get(0)));
        if (enterprise == null) {
            return ResultUtil.error("企业不存在！");
        }
        SessionKeyUtils.setSessionEnterprise(request, enterprise);
        systemUserBiz.getNewAuth(enterprise);
        return ResultUtil.success();
    }


}
